/**
 * Created by yang.fan on 2017/11/17.
 */
import React from 'react';
import {Modal, Button,Row,Col,Cascader,Input,Form,message} from 'antd';
import styles  from './PredictMap.less';
import { request } from '../../config/request'
const { Component } = React
import { cloneDeep,isEqual } from 'lodash';
// 引入全局配置
import config from '../../config/config'
import $ from 'jquery'

let count = 0, libs = [
  'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
  'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
];
const head = document.getElementsByTagName('head')[0];
/*
 *
 * 地图组件
 *
 */

export default class Bmap extends Component {
    constructor(props) { //用于初始化state
      super(props);
   
      this.setMapRef = ref => {
        this.mapContainer = ref;
      };
      this.state = {
        markers:[],
        // 地图实例
        map: null,
        address: this.props.address||'',
        latAndLon: this.props.latAndLon || [113.437218, 23.103965],
        //开启关闭按钮
        mapVisible: this.props.visible || false,
        flag: false,
        flag1:false,
        firstFlag: true,
        actionType: this.props.actionType || 'add',
        //确定按钮
        cbk: (rs)=>{
          this.props.cbk(rs);
        },
        // mapListFun: (rs)=>{
        //   this.props.mapListFun(rs);
        // },
      }
    }
    // 组件挂载后调用
    // 可以在该函数中进行请求或者订阅
    async componentDidMount() {
        if(!this.map){
          this.createMapScript().then(this.initMap);
        }
    }
    //父组件中改变了props传值时触发的函数
    componentWillReceiveProps(nextProps) {
      if(nextProps.visible){ 
        if(this.map){
            this.addOverlayGroup(nextProps)
        }else{
            //tabs切换 组件已销毁，但是地图资源已加载，不需要再次加载地图资源
            this.initMap(nextProps)
        }
      }
      if(this.state.actionType == 'add'&&this.state.firstFlag){
        this.initMap(nextProps)
      }
      this.state.firstFlag = false
      this.state.oldAddress = JSON.parse(JSON.stringify(nextProps.address))
    }
    addOverlayGroup(payload){
      var _this = this

      let {map,maps,markerClusterer} = _this
      map.clearOverlays();
      var point = new BMap.Point(payload.latAndLon[1],payload.latAndLon[0]);
      // var point = payload.latAndLon
      map.centerAndZoom(point, 18);
      map.addOverlay(new BMap.Marker(point, {title: payload.address}))
      // var myGeo = new BMap.Geocoder();
      // myGeo.getPoint(payload.address, function(point){
      //   if(point){
      //       map.centerAndZoom(point, 18);
      //       map.addOverlay(new BMap.Marker(point, {title: payload.address}))
      //       let pram ={
      //         address:payload.address,
      //         point:point
      //       }
      //       if(!_this.state.flag){
      //         _this.state.cbk(pram);
      //       }
      //       _this.state.flag = true
      //   }else{
      //       alert('您选择的地址没有解析到结果！');
      //   }
      // })
      // 百度地图API功能
      let options = {
        onSearchComplete: function(results){
          // 判断状态是否正确
          if (local.getStatus() == BMAP_STATUS_SUCCESS){
            var s = [];
            for (var i = 0; i < results.getCurrentNumPois(); i ++){
              let obj = {
                title:results.getPoi(i).title,
                address: results.getPoi(i).address,
                point: results.getPoi(i).point,
              }
              s.push(obj);
            }
              localStorage.setItem('qianceMapList',JSON.stringify(s))
          }
        }
      }
      let local = new BMap.LocalSearch(map,options);
      local.search(payload.address)
    }
    // 判断是否需要更新组件，多用于组件性能优化,使用后不会重新加载
    shouldComponentUpdate() {
      return !this.inited;
    }
    //组件挂载完成时触发的函数
    componentWillUnmount() {
      if (this.map) {
        this.map = null;
      }
      if (this.map) {
        this.maps = null
      }
      if(this.markerClusterer){
        this.markerClusterer = null
      }
    }
    initMap=()=>{

      let {BMap,BMapLib={}} = window
      let that = this
      
      // 百度地图API功能
      var map = new BMap.Map(this.mapContainer);
      var maps = BMapLib
      if(that.state.actionType == 'add'){
        map.clearOverlays();
        var point = new BMap.Point(113.437218,23.103965); 
        map.centerAndZoom(point,5);
        map.setDefaultCursor('pointer');
        map.enableScrollWheelZoom();
        map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
        map.addControl(new BMap.NavigationControl());
      }
      if(that.state.actionType== 'check'||that.state.actionType== 'edit'){
        var point = new BMap.Point(that.state.latAndLon[1], that.state.latAndLon[0]); 
        map.centerAndZoom(point,18);
        map.setDefaultCursor('pointer');
        map.enableScrollWheelZoom();
        map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
        map.addControl(new BMap.NavigationControl());
        map.clearOverlays();
        var marker = new BMap.Marker(point);
        map.addOverlay(marker);
      }
      //创建一个地址解析器的实例
      var geoc = new BMap.Geocoder();
      //为地图实例添加了一个鼠标单击的监听事件
      map.addEventListener("click",function(e){
          map.clearOverlays();
          //事件参数e中保存了鼠标单击时所对应的地理位置point
          var pt = e.point;
          var marker = new BMap.Marker(new BMap.Point(pt.lng, pt.lat));
          map.addOverlay(marker);
          //将鼠标单击时的坐标进行逆地址解析
          geoc.getLocation(pt,function(rs){//解析的结果是一个对象，且作为参数传入了回调函数中
              //该对象的属性中保存了解析后的结构化的地址信息
              that.state.cbk(rs);
          })
      });
     
      this.map = map
      this.maps = maps

    };
    createMapScript = () =>{
      var self = this
      const ak = 'ORYNu4GTZHUUg8uT4rXuzfDMxQNvGGY1';
      return new Promise((resolve, reject) => {
        if (window.BMap && Window.BMapLib) {
            // 已经加载则直接返回
            console.log('map already exist');
            resolve({BMap: window.BMap, BMapLib: window.BMapLib});
        } else {
            // 异步加载
            console.log('async load map');
            const bmap = document.createElement('script');
            bmap.type = 'text/javascript';
            bmap.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=MapLoadSuccess`;

            const bmapMeta = document.createElement('meta');
            bmapMeta['http-equiv'] = "Content-Security-Policy";
            bmapMeta['content']="upgrade-insecure-requests";

            head.appendChild(bmap);
            window.MapLoadSuccess = function() {
                // BMap加载完成，开始加载libs
                libs.forEach(lib => {
                  self.loadLib(lib, resolve, reject);
                })
            }
            bmap.onerror = function() {
                reject('地图初始化失败');
            }
        }
    })
    }

    loadLib(src, resolve, reject) {
      const lib = document.createElement('script');
      lib.setAttribute('type', 'text/javascript');
      lib.setAttribute('src', src);
      lib.onerror = function() {
          reject('地图初始化失败');
      }
      lib.onload = function() {
          count += 1;
          if (count === libs.length) { // libs全部加载成功才返回
              resolve({BMap: window.BMap, BMapLib: window.BMapLib});
          }
      }
      head.appendChild(lib);
  }
  
    render() {
      const { width = '100%', height = 700, style } = this.props;
  
      return (
        <div style={{ border: 'solid 1px #e1e1e1', marginBottom: 16, borderRadius: 5 }}>
          <div ref={this.setMapRef} style={{ width, height, ...style }} />
        </div>
      );
    }
  }


